<template>
  <div class="header-container">
    <div class="header">
      <div class="header-top">
        <div class="header-logo" @click="navToHome">
          <img src="../assets/img/logo.png" alt>
        </div>
        <div class="header-nav">
          <van-icon name="cross" v-if="navShow" @click="closeNav"/>
          <van-icon name="wap-nav" v-else @click="openNav"/>
        </div>
        <div class="nav-list" v-if="navShow">
          <div class="nav-item" v-if="isLogined">
            <div class="login-info">
              <div class="user-pic" v-if="loginInfo.Image">
                <img :src="loginInfo.Image" alt>
              </div>
              <div class="user-name" v-if="loginInfo.NickName">{{loginInfo.NickName}}</div>
            </div>
          </div>
          <div class="nav-item">
            <a href="#/">{{$t('message.header.home')}}</a>
          </div>
          <div class="nav-item" v-if="isLogined">
            <a href="javascript:;" @click="toUserInfo">{{$t('message.header.personal')}}</a>
          </div> 
          <div class="nav-item" v-else>
            <a href="javascript:;" @click="goLogin">{{$t('message.header.login')}}</a>
          </div>
          <div class="nav-item">
            <a href="javascript:;" @click="NavigateTo">{{$t('message.header.joined')}}</a>
          </div>
          <div class="nav-item" v-if="isLogined">
            <a href="javascript:;" @click="quitLogin">{{$t('message.header.quit')}}</a>
          </div>
          <div class="nav-item" v-else>
            <a href="#/register">{{$t('message.header.register')}}</a>
          </div>
          <div class="nav-item" v-if="isBilingual">
            <a class="lang-btn" href="javascript:;" @click="checkLang">{{$t('message.language')}}</a>
          </div>           
          <!-- <div class="nav-item">
            <a href="javascript:;">关于我们</a>
          </div>            -->
        </div>
      </div>
    </div>
    <div class="mask" v-if="navShow" @click="closeNav"></div>
  </div>
</template>

<script>
import $ from 'jquery';
export default {
  data() {
    return {
      navShow: false,
      isLogined: this.$cookies.isKey('token'),
      screenWidth: null,
      loginInfo: {},
      locale: 'CN',
      isBilingual: this.$store.state.IsBilingual
    };
  },
  created() {
    if (this.$route.query.token) {
      this.$cookies.set('token', this.$route.query.token, 8 * 60 * 60);
      localStorage.setItem('token', this.$route.query.token);
      this.isLogined = true;
      this.getLoginInfo(this.$route.query.token);
    }
    if (this.$route.query.code) {
      // PC扫码登录
      var that = this;
      $.ajax({
        type: 'GET',
        url: `${that.baseUrl}/api/login/wxlogin?code=${
          this.$route.query.code
        }&state=${this.$route.query.state}`,
        success: function(res) {
          if (res.State) {
            that.$cookies.set('token', res.Data, 8 * 60 * 60);
            localStorage.setItem('token', res.Data);
            that.$store.commit('SET_TOKEN', res.Data);
            that.isLogined = true;
            that.getLoginInfo(res.Data);
          }
        }
      });
    }
    if (this.$route.query.OpenID) {
      localStorage.setItem('OpenId', this.$route.query.OpenID);
      this.$store.commit('SET_OPENID', this.$route.query.OpenID);
    }
    if (this.$cookies.isKey('token')) {
      this.isLogined = true;
      let token = this.$cookies.get('token');
      this.getLoginInfo(token);
    } else {
      this.isLogined = false;
    }
      this.screenWidth = window.screen.width;
      if (window.screen.width > 768) {
        this.navShow = true;
      } else {
        this.navShow = false;
      }
  },
  mounted() {
    var that = this;
    window.onresize = () => {
        that.screenWidth = document.body.clientWidth;
    };
  },
  methods: {
    checkLang() {
      if (this.locale == 'CN') {
        this.locale = 'EN';
        this.$i18n.locale = this.locale;
      } else {
        this.locale = 'CN';
        this.$i18n.locale = this.locale;
      }
    },
    toUserInfo() {
      if (this.$cookies.isKey('token')) {
        window.location.href = '#/user';
      } else {
        this.$toast('请先登录');
      }
    },
    navToHome() {
      window.location.href = '#/';
    },
    deleteQuery() {
      let query = JSON.parse(JSON.stringify(this.$route.query));
      if (query.OpenID) {
        delete query.OpenID;
      }
      if (query.token) {
        delete query.token;
      }
      if (query.code) {
        delete query.code;
      }
      if (query.state) {
        delete query.state;
      }
      return query;
    },
    getLoginInfo(token) {
      var that = this;
      $.ajax({
        type: 'GET',
        url: that.baseUrl + '/api/account/get',
        headers: { 'Authorization': token },
        success: function(res) {
          if (res.State) {
            that.loginInfo = res;
            if (res.Unionid) {
              localStorage.setItem('Unionid', res.Unionid);
              that.$store.commit('SET_UNIONID', res.Unionid);
            }
            if (res.Openid) {
              localStorage.setItem('OpenId', res.Openid);
              that.$store.commit('SET_OPENID', res.Openid);
            }
          } else {
            that.$toast(res.Message);
            that.isLogined = false;
            that.$cookies.remove('token');
            that.$router.push({query: that.deleteQuery()});
            window.location.reload();
          }
        },
        fail: function(err) {
          window.$Raven.captureException(err);
        }
      });
    },
    goLogin() {
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        this.$dialog.alert({
        title: '离成功只差登录',
        confirmButtonText: '微信一键登录'
      }).then(() => {
        window.location.href = `http://es.11cm.com.cn/WeiXinManage/GetWeiXinOpenID?ST=test&ReferrerUrl=${encodeURIComponent(window.location.href)}`;
      });
      } else {
        window.location.href = `#/login?&ReferrerUrl=${encodeURIComponent(window.location.href)}`;
      }
    },
    quitLogin() {
      let token = this.$cookies.get('token');
      var that = this;
      $.ajax({
        type: 'GET',
        url: `${that.baseUrl}/api/account/logout`,
        headers: { 'Authorization': token },
        success: function(res) {
          if (res.State) {
            that.isLogined = false;
            that.$cookies.remove('token');
            localStorage.removeItem('token');
            window.location.href = '#/';
          } else {
            that.$toast(res.Message);
          }
        },
        error: function(err) {
          console.log(err);
        }
      });
    },
    openNav() {
      this.navShow = true;
    },
    closeNav() {
      this.navShow = false;
    },
    NavigateTo() {
      if (this.$cookies.isKey('token')) {
        window.location.href = '#/record';
      } else {
        this.$toast('请先登录！');
      }
    }
  },
  watch: {
    locale: function(val, oldVal) {
      if (val) {
        this.$i18n.locale = val;
      }
    },
      'screenWidth': function(val, oldVal) {
          if (val > 768) {
              this.navShow = true;
          } else {
              this.navShow = false;
          }
      },
      $route: {
        handler: function(val, oldVal) {
          if (val.query.token) {
            this.$cookies.set('token', val.query.token, 8 * 60 * 60);
            localStorage.setItem('token', val.query.token);
            this.isLogined = true;
            this.getLoginInfo(val.query.token);
          }
          if (val.query.code) {
            // PC扫码登录
            var that = this;
            $.ajax({
              type: 'GET',
              url: `${that.baseUrl}/api/login/wxlogin?code=${
                val.query.code
              }&state=${val.query.state}`,
              success: function(res) {
                if (res.State) {
                  that.$cookies.set('token', res.Data, 8 * 60 * 60);
                  localStorage.setItem('token', res.Data);
                  that.$store.commit('SET_TOKEN', res.Data);
                  that.isLogined = true;
                  that.getLoginInfo(res.Data);
                }
              }
            });
          }
        },
        deep: true
      }

  }
};
</script>

<style scoped>
a.lang-btn{
    max-width: 40px;
    width: auto;
    display: inline-block;
    padding: 0 5px;
    font-size: 14px;
    line-height: 22px;
    border-radius: 3px;
    /* text-align: center; */
    color: #455a64;
    /* border: 1px solid #455a64; */
    font-family: Helvetica Neue,Arial,sans-serif;
}
</style>
